<script setup>
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue'
import { ref ,onBeforeMount, reactive, toRefs} from 'vue';
import { da } from 'element-plus/es/locales.mjs';
import { listHandler } from '../../api/generic.js';
import { deleteTableRow } from '../../utils/utils';
import Table from '../components/Table.vue';
import { object2List,list2Object } from '../../utils/utils';
// import DialogYaml from '../components/DialogYaml.vue';
// import { obj2Yaml } from '../../utils/utils';
import { updateServiceHandler as updateHandler, createServiceHandler as createHandler,getServiceListHandler } from '../../api/service';
import {useRouter} from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})

const data = reactive({
  clusterId: '',
  namespace: '',
  item: {
    apiVersion: 'v1',
    kind: 'Service',
    metadata: {
      name: '',
      namespace: '',
      labels: {},
      annotations: {}
    },
    spec: {
      ports: [
        
      ],
      selector: {},
      type: 'ClusterIP',
      sessionAffinity: "None"
    }
    },
  options: {
    proxyResourceTypeSelected: '',
    proxyResourceTypes: [
      {
        value: 'Deployment',
        label: 'Deployment'
      },
      {
        value: 'StatefulSet',
        label: 'StatefulSet'
      },
      {
        value: 'DaemonSet',
        label: 'DaemonSet'
      },
      {
        value: 'ExternalName',
        label: '外部域名'
      }  
    ],
    items:[],
    item:{},
    serviceTypes: [
      {
        value: 'ClusterIP',
        label: 'ClusterIP'
      },
      {
        value: 'NodePort',
        label: 'NodePort'
      },
      {
        value: 'LoadBalancer',
        label: 'LoadBalancer'
      },
    ],
    labelList:[],
    annotationsList:[],
    podLabelList: [],
    rules: {
      name: [
            {required: true, message: '请输入Service名称', trigger: 'blur'}
        ],
      externalName: [
          {required: true, message: '请输入代理的域名', trigger: 'blur'}
      ],
    }
  }
})
const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
let yamlContent = ref('')
let showDetail = ref(false)

const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/service/list',
        query: {
          clusterId: data.clusterId,
          namespace: data.namespace
        }
      })
    })
    .catch(() => {
      return
    })
}

const submitHandler = (tag) => {
  console.log('tag:', tag)
  console.log('item:', data.item)
  //把list转成object
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationsList)
  if (data.item.spec.type != 'ExternalName'){
    data.item.spec.selector = list2Object(data.options.podLabelList)
  }
  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: data.item,
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
          // loading.value = false
          // emits('rollback')
        })
  } else {
      // 创建用户，异步的
      updateHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}

const submit = (tag)=> {
    itemRef.value.validate((valid)=>{
        // valid => true
        if(!valid){
        ElMessage({
                    message: "请完善表单内容",
                    type: 'warning',
                })
        }else {
          submitHandler(tag)
        }
    })
}
const namespaceChangeHandler = (clusterId, namespace)=>{
  console.log('namespaceChangeHandler:', clusterId, namespace)
  data.clusterId = clusterId
  data.namespace = namespace
  data.item.metadata.namespace = namespace
  //刷新一下资源列表
  if (data.options.proxyResourceTypeSelected != 'ExternalName' && data.options.proxyResourceTypeSelected != ''){
    getResourceList
  }
}
const getResourceList = async()=>{
  console.log("获取资源列表:",data.clusterId, data.namespace,data.options.proxyResourceTypeSelected)
  await listHandler(data.clusterId, 
  data.namespace, 
  data.options.proxyResourceTypeSelected).then((res)=>{
    console.log("获取资源列表:",res.data.data.items)
    //清空之前的值
    data.options.item = {}
    data.options.items = res.data.data.items
  })
}
const proxyResourceTypeChanged = (val)=>{
  console.log("选择代理的类型是", val)
  if (val == 'ExternalName') {
    data.options.item ={}
    const serviceSpec = {
      type: 'ExternalName',
      externalName: ''
    }
    data.item.spec = serviceSpec

    return
  }else{
    delete data.item.spec.externalName
    data.item.spec.type = 'ClusterIP'
    getResourceList()
  }
}
const headlessServiceChanged = (val)=>{
  console.log("无头服务",val)
  if(!val){
    delete data.item.spec.clusterIP
  }
}
const sessionChanged = (val)=>{
  //会话保持处理
  if(val == 'None'){
    //表示关闭会话保持
    data.item.spec.sessionAffinity = 'None'
    delete data.item.spec.sessionAffinityConfig
  }else{
    data.item.spec.sessionAffinity = 'ClientIP'
    data.item.spec.sessionAffinityConfig = {
      clientIP:{
        timeoutSeconds:3600
      }
    }
  }
}
//选择的资源产生变化的处理函数
const proxyResourceChanged = ()=>{
  console.log("选择代理的资源产生变化")
  data.item.metadata.name = data.options.item.metadata.name
  const containers = data.options.item.spec.template.spec.containers
  data.item.spec.ports = []
  for(let c=0;c<containers.length;c++){
    const container = containers[c]
    const containerPorts = container.ports
    if(!containerPorts){continue}
    for(let p=0;p<containerPorts.length;p++){
      const containerPort = containerPorts[p]
      const servicePort = {
        name: containerPort.name,
        port: containerPort.containerPort,
        protocol: containerPort.protocol,
        targetPort: containerPort.containerPort
      }
      data.item.spec.ports.unshift(servicePort)
    }
  }
  //处理标签等配置
  data.options.labelList = object2List(data.options.item.metadata.labels)
  data.options.podLabelList = object2List(data.options.item.spec.template.metadata.labels)
  data.options.annotationsList = object2List(data.options.item.metadata.annotations)
}
//添加端口
const addPort = ()=>{ 
  if (data.item.spec.ports == undefined || data.item.spec.ports == null){
    data.item.spec.ports = []
  }
  const port = {
    port: 80,
    name: '',
    targetPort: 8080,
    protocol: 'TCP'
  }
  data.item.spec.ports.unshift(port)
}
const serviceTypeChanged = (val)=>{ 
  if (data.item.spec.type == 'ClusterIP'){
    console.log("删除nodePort配置")
    data.item.spec.ports.forEach((port)=>{
      delete port.nodePort
    })
  }
}
onBeforeMount(()=>{
  if (props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationsList = object2List(data.item.metadata.annotations)
    if(data.item.spec.type != 'ExternalName'){
      data.options.podLabelList = object2List(data.item.spec.selector)
    }
  }
})  
const {options,item,clusterId,namespace} = toRefs(data)
</script>

<template>
  <CreateOrEditFrame
  :namespace-readonly="props.method == 'Update'"
  :cluster-readonly="props.method == 'Update'"
  @namespace-changed-rollback="namespaceChangeHandler"
  >
  <!-- 头部插入内容 -->
   <template #header>
    <!-- 选择类型 -->
    <el-select style="margin-left: 10px; width: 180px;" 
    v-if="props.method == 'Create'" 
    v-model="options.proxyResourceTypeSelected" 
    placeholder="选择代理的类型"
    @change="proxyResourceTypeChanged"
    >
        <el-option v-for="t in options.proxyResourceTypes" 
        :key="t.value" 
        :label="t.label" 
        :value="t.value">
        </el-option>
    </el-select>
<!-- 选择资源名称 -->
    <el-select style="margin-left: 10px; width: 180px;" 
    v-if="props.method == 'Create' && options.proxyResourceTypeSelected != 'ExternalName'" 
    v-model="options.item" 
    value-key="metadata.name"
    placeholder="选择代理的资源"
    @change="proxyResourceChanged"
    >
        <el-option v-for="t in options.items" 
        :key="t.metadata.name" 
        :label="t.metadata.name" 
        :value="t">
        </el-option>
    </el-select>
   </template>
   <template #main>
    <el-form :model="item"
    ref="itemRef">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="基本配置" name="basic" style="height: 240px;">
        <el-row :gutter="20">
          <el-col :span="6">
              <el-form-item  :rules="options.rules.name" label="Service名称" prop="metadata.name" required>
                  <el-input :disabled="props.method == 'Update'"  v-model="item.metadata.name"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="5" v-show="options.proxyResourceTypeSelected != 'ExternalName'">
              <el-form-item  label="Service类型" prop="" >
                <el-select v-model="item.spec.type" style="width: 180px;" placeholder="选择Service类型" @change="serviceTypeChanged">
                      <el-option
                      v-for="s in options.serviceTypes"
                      :key="s.value"
                      :label="s.label"
                      :value="s.value"
                      />
                  </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="3" v-show="item.spec.type !='ExternalName' && item.spec.type == 'ClusterIP'">
              <el-form-item  label="无头服务" prop="" >
                <el-switch v-model="item.spec.clusterIP" active-value="None" @change="headlessServiceChanged"></el-switch>
              </el-form-item>
          </el-col>
          <el-col :span="2" v-show="item.spec.type !='ExternalName'">
              <el-form-item  label="会话保持" prop="" >
                <el-switch v-model="item.spec.sessionAffinity" active-value="ClientIP" inactive-value="None" @change="sessionChanged"></el-switch>
              </el-form-item>
          </el-col>
          <el-col :span="6" v-if="item.spec.type !='ExternalName'&&item.spec.sessionAffinity == 'ClientIP'">
              <el-form-item  label="会话保持时间" prop="">
                <el-input-number :min="1" :controls="false" v-model="item.spec.sessionAffinityConfig.clientIP.timeoutSeconds" ></el-input-number>
              </el-form-item>
          </el-col>
          <el-col :span="6" v-if="item.spec.type == 'ExternalName'">
              <el-form-item :rules="options.rules.externalName" required label="请输入代理的目标域名" prop="spec.externalName" >
                  <el-input  v-model="item.spec.externalName"></el-input>
              </el-form-item>
          </el-col>
        </el-row>

      </el-tab-pane>
      <el-tab-pane 
      label="端口配置" 
      name="ports" 
      v-if="options.proxyResourceTypeSelected != 'ExternalName'">
      <el-form-item style="width: 100;">
        <el-table
        :data="item.spec.ports"
        border       
        >
        <el-table-column label="端口名称" title="Service端口名称" width="180px" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.name" placeholder="Service端口名称"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="协议" title="代理的协议" width="180px" align="center">
          <template #default="scope">
            <el-select 
            v-model="scope.row.protocol" 
            placeholder="协议">
                <el-option v-for="p in ['TCP','UDP','SCTP']" 
                :key="p" 
                :label="p" 
                :value="p">
                </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="程序端口" title="应用程序的端口" width="180px" align="center">
          <template #default="scope">
            <StringOrNumber :key="scope.row.port" input-width="100%" v-model:data="scope.row.targetPort" placeholder="应用程序端口"></StringOrNumber>
          </template>
        </el-table-column>
        <el-table-column label="Service端口"  title="Service端口" width="240px" align="center">
          <template #default="scope">
            <el-form-item required label="" :prop="('spec.ports.'+scope.$index+'.port')">
              <el-input-number style="width: 100%;" v-model="scope.row.port" :min="1" :max="65535" placeholder="Service端口"></el-input-number>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="NodePort" title="在宿主机上暴露的端口号" width="240px" align="center">
          <template #default="scope">
            <el-input-number style="width: 100%;" :disabled="item.spec.type == 'CLusterIP'"  v-model="scope.row.nodePort" :min="1" :max="65535" placeholder="Service端口"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
          <template #header>
            <el-button link type="primary" @click="addPort()">添加</el-button>
          </template>
          <template #default="scope">
            <el-button link type="warning" @click="deleteTableRow(item.spec.ports,scope.$index)">删除</el-button>
          </template>
        </el-table-column>
        </el-table>
      </el-form-item>
    
      </el-tab-pane>
      <el-tab-pane label="注释及标签" name="labels">
        <el-tabs v-model="labelConfig" tabPosition="left">
            <el-tab-pane label="Service标签配置" name="labels">
              <Table :list="options.labelList"></Table>
            </el-tab-pane>
            <el-tab-pane label="Service注释配置" name="annos">
              <Table :list="options.annotationsList"></Table>
            </el-tab-pane>
            <el-tab-pane label="代理的Pod标签" name="pod-labels" v-if="item.spec.type != 'ExternalName'">
              <Table :list="options.podLabelList"></Table>
            </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>

    <!-- yaml,创建 -->
       <el-form-item class="button-container">
     <div class="button-wrapper"> <!-- 新增包裹层 -->
      <el-button @click="submit('yaml')">Yaml</el-button>
      <el-button type="primary" @click="submit()">
        {{ props.method=="Update" ? "更新" : "创建" }}
      </el-button>
    </div>
  </el-form-item>
    </el-form>
   </template>

  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  :method="props.method"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
</template>

<style scoped>
.button-container {
  /* 去除表单组件默认内边距 */
  padding: 0 !important;
  text-align: center; /* 辅助居中 */
}

.button-wrapper {
  /* 弹性布局容器 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  gap: 10px; /* 按钮间距 */
  padding: 20px; /* 添加自定义内边距 */
  width: 100%; /* 占满父容器宽度 */
}
</style>
